 package com.sws.weixin.service.impl;

import com.sws.weixin.entity.RyStaff;
import com.sws.weixin.mapper.RyStaff2Mapper;
import com.sws.weixin.service.StaffWxBinder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * 工作人员微信绑定服务实现类(微信模块)
 */
@Service
public class WxStaffBinderImpl implements StaffWxBinder {

    @Autowired
    private RyStaff2Mapper ryStaffMapper;
    
    @Override
    @Transactional
    public Map<String, Object> bindWxUserToStaff(String name, String phone, String openid) {
        Map<String, Object> result = new HashMap<>();
        
        // 检查openid是否已经绑定
        RyStaff existingStaff = ryStaffMapper.selectByOpenid(openid);
        if (existingStaff != null) {
            result.put("success", false);
            result.put("msg", "此微信号已绑定，请勿重复操作");
            return result;
        }
        
        // 根据姓名和手机号查找工作人员
        RyStaff staff = ryStaffMapper.selectByNameAndPhone(name, phone);
        if (staff == null) {
            result.put("success", false);
            result.put("msg", "未找到对应的工作人员信息，请确认姓名和手机号是否正确");
            return result;
        }
        
        // 如果工作人员已绑定其他微信号
        if (staff.getOpenid() != null && !staff.getOpenid().isEmpty()) {
            result.put("success", false);
            result.put("msg", "该工作人员已绑定其他微信号，请联系管理员");
            return result;
        }
        
        // 更新工作人员表，绑定微信号
        int updated = ryStaffMapper.updateOpenid(staff.getId(), openid);
        if (updated > 0) {
            result.put("success", true);
            result.put("msg", "工作人员认证成功！");
            return result;
        } else {
            result.put("success", false);
            result.put("msg", "认证失败，请稍后再试");
            return result;
        }
    }

    @Override
    public Map<String, Object> verifyStaffIdentity(String openid) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 根据openid查询工作人员记录
            RyStaff staff = ryStaffMapper.selectByOpenid(openid);
            
            if (staff != null) {
                result.put("success", true);
                result.put("staffInfo", staff);
                return result;
            }
            
            result.put("success", false);
            result.put("msg", "未找到绑定的工作人员信息");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "验证身份失败：" + e.getMessage());
        }
        
        return result;
    }

    @Override
    public Map<String, Object> getStaffCustomers(String staffPid) {
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("customers", new HashMap<>());
        return result;
    }
} 